package dataGoods

import (
	"context"
	goods_pb "mxshop/api/goods/v1"
	IGoods "mxshop/app/mxshop_api/api/internal/data/goods"
	doGoods "mxshop/app/mxshop_api/api/internal/domain/do/goods"
	"mxshop/gmicro/pkg/errors"
)

type categoryBrand struct {
	gc goods_pb.GoodsClient
}

func (cb *categoryBrand) List(ctx context.Context, req *goods_pb.CategoryBrandFilterRequest) (*doGoods.CategoryBrandDOList, error) {
	var ret doGoods.CategoryBrandDOList

	rsp, err := cb.gc.CategoryBrandList(ctx, req)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Data {
		ret.Items = append(ret.Items, &doGoods.CategoryBrandDO{
			Id:         v.Id,
			CategoryId: v.Category.Id,
			BrandId:    v.Brand.Id,
		})
	}
	ret.TotalCount = rsp.Total
	return &ret, nil
}

func (cb *categoryBrand) Get(ctx context.Context, ID int64) (*doGoods.BrandDOList, error) {
	var ret doGoods.BrandDOList

	rsp, err := cb.gc.GetCategoryBrandList(ctx, &goods_pb.CategoryInfoRequest{Id: ID})
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Data {
		ret.Items = append(ret.Items, &doGoods.BrandDO{
			Id:   v.Id,
			Name: v.Name,
			Logo: v.Logo,
		})
	}

	return &ret, nil
}

func (cb *categoryBrand) Create(ctx context.Context, req *doGoods.CategoryBrandDO) (*doGoods.CategoryBrandDO, error) {
	var ret doGoods.CategoryBrandDO

	rsp, err := cb.gc.CreateCategoryBrand(ctx, &goods_pb.CategoryBrandRequest{
		CategoryId: req.CategoryId,
		BrandId:    req.BrandId,
	})
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	ret.Id = rsp.Id

	return &ret, nil
}

func (cb *categoryBrand) Update(ctx context.Context, req *doGoods.CategoryBrandDO) error {
	_, err := cb.gc.UpdateCategoryBrand(ctx, &goods_pb.CategoryBrandRequest{
		Id:         req.Id,
		CategoryId: req.CategoryId,
		BrandId:    req.BrandId,
	})
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func (cb *categoryBrand) Delete(ctx context.Context, ID int64) error {
	_, err := cb.gc.DeleteCategoryBrand(ctx, &goods_pb.CategoryBrandRequest{Id: ID})
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func newCategoryBrand(gc goods_pb.GoodsClient) IGoods.CategoryBrand {
	return &categoryBrand{
		gc: gc,
	}
}
